<template>
  <div>
    <div id="userPic" style="margin-top: 20px; text-align: center">
      <!-- 用户上传照片作为头像 图片显示失败 -->
      <img
        :src="avatarUrl"
        v-if="
          userInfo.avatar != null && userInfo.avatar != '' && userInfo.avatar != undefined
        "
        :title="userInfo.name"
        style="vertical-align: middle; width: 80px; height: 80px"
      />
      <avatar
        v-else
        :username="userInfo.name"
        :size="85"
        style="margin-top: 10px; margin-left: 47.5%; vertical-align: middle"
        :title="userInfo.name"
      />
      <p style="margin-bottom: 20px"></p>
      <h1 style="display: inline-block">欢迎,</h1>
      <!-- <h1 style="color: #2d8cf0;display: inline-block;" v-show="userInfo.title!=''">{{userInfo.title}}. </h1> -->
      <h1 style="color: #2d8cf0; display: inline-block">{{ userInfo.name }}</h1>
      <p style="margin-bottom: 20px"></p>
    </div>
    <Row>
      <Col span="23" offset="1">
        <div>
          <Card style="height: 50%; width: 50%; margin: auto" class="userInfoCard">
            <List style="margin: 6% 0">
              <ListItem>
                <span class="uTitle">学号</span>
                <div class="uAlign">
                  <span class="uContent">{{ userInfo.userId }}</span>
                </div>
              </ListItem>
              <ListItem>
                <span class="uTitle">姓名</span>
                <div class="uAlign">
                  <span class="uContent">{{ userInfo.name }}</span>
                </div>
              </ListItem>
              <!-- <ListItem>
                  <span class="uTitle">电话</span>
                  <div class="uAlign">
                    <span class="uContent">{{userInfo.phone}}</span>
                  </div>
                </ListItem> -->
              <ListItem>
                <span class="uTitle">专业</span>
                <div class="uAlign">
                  <span class="uContent">{{ userInfo.subject }}</span>
                </div>
              </ListItem>
              <ListItem>
                <span class="uTitle">学院</span>
                <div class="uAlign">
                  <span class="uContent">{{ userInfo.college }}</span>
                </div>
              </ListItem>
            </List>
            <div style="margin-top: 5%">
              <Button
                @click="showEditUserInfoModal"
                type="info"
                style="width: 86%; margin-left: 7%"
                >修改个人信息</Button
              >
              <br />
              <Button
                @click="showResetPwdModal"
                type="success"
                style="margin-top: 10px; width: 86%; margin-left: 7%"
                >修改密码</Button
              >
            </div>
          </Card>
        </div>
      </Col>
    </Row>

    <Modal v-model="editUserInfoModal" title="修改个人信息" width="600">
      <div style="margin-top: 25px">
        <Form :model="userInfoFormItems" :label-width="80">
          <FormItem label="姓名">
            <Input v-model="userInfoFormItems.name" style="width: 85%; margin-left: 10px">
            </Input>
          </FormItem>
          <FormItem label="专业">
            <Input
              v-model="userInfoFormItems.subject"
              style="width: 85%; margin-left: 10px"
            ></Input>
          </FormItem>
          <FormItem label="学院">
            <Input
              v-model="userInfoFormItems.college"
              style="width: 85%; margin-left: 10px"
            ></Input>
          </FormItem>
          <FormItem label="头像">
            <div style="margin-left: 10px">
              <!-- 显示用户原始头像信息 -->
              <div
                class="demo-upload-list"
                v-if="
                  userInfoFormItems.avatar != '' &&
                  userInfoFormItems.avatar != null &&
                  userInfoFormItems.avatar != undefined &&
                  !reUpload
                "
              >
                <template>
                  <img v-bind:src="avatarUrl" class="avatarImage" />
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
                  </div>
                </template>
              </div>
              <!-- 显示用户新上传的头像信息 -->
              <div
                class="demo-upload-list"
                v-if="
                  userInfoFormItems.avatar != '' &&
                  userInfoFormItems.avatar != null &&
                  userInfoFormItems.avatar != undefined &&
                  reUpload
                "
              >
                <template>
                  <img v-bind:src="userInfoFormItems.avatar" class="avatarImage" />
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
                  </div>
                </template>
              </div>

              <div class="uploadBox">
                <Icon
                  type="ios-camera"
                  size="20"
                  style="position: absolute; margin: 18px"
                ></Icon>
                <input
                  id="choosePicture"
                  @change="uploadPhoto($event)"
                  type="file"
                  class="uploadAvatar"
                />
              </div>

              <Modal title="View Image" v-model="visible" v-if="!reUpload">
                <img :src="avatarUrl" v-if="visible" style="width: 100%" />
              </Modal>
              <Modal title="View Image" v-model="visible" v-if="reUpload">
                <img :src="userInfoFormItems.avatar" v-if="visible" style="width: 100%" />
              </Modal>
            </div>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="editUserInfoModal = false">取消</Button>
        <Button type="primary" @click="updateUserInfo">保存修改 </Button>
      </div>
    </Modal>

    <Modal v-model="resetPasswordModal">
      <Form ref="formValidate" :model="resetPwdFormItems" :rules="resetPwdRuleValidate">
        <FormItem label="输入旧密码" prop="oldPwd">
          <Input
            v-model="resetPwdFormItems.oldPwd"
            type="password"
            placeholder="输入旧密码"
          >
          </Input>
        </FormItem>
        <FormItem label="输入新密码" prop="newPwd">
          <Input
            v-model="resetPwdFormItems.newPwd"
            type="password"
            placeholder="输入新密码"
          >
          </Input>
        </FormItem>
        <FormItem label="确认新密码" prop="validPwd">
          <Input
            v-model="resetPwdFormItems.validPwd"
            type="password"
            placeholder="确认新密码"
          ></Input>
        </FormItem>
      </Form>
      <Button
        slot="footer"
        type="primary"
        @click="resetPwd()"
        :disabled="
          resetPwdFormItems.newPwd != resetPwdFormItems.validPwd ||
          resetPwdFormItems.oldPwd == '' ||
          resetPwdFormItems.newPwd == ''
        "
        >确认
      </Button>
    </Modal>
  </div>
</template>

<script>
import Avatar from "vue-avatar";
import md5 from "js-md5";
import VueTagsInput from "@johmun/vue-tags-input";
import { get, post, del, put } from "@/axios";
// import image2Base64 from 'image-to-base64/browser'

export default {
  name: "userInfo",
  components: {
    Avatar,
    VueTagsInput,
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value !== this.resetPwdFormItems.newPwd) {
        callback(new Error("确认密码与密码输入不一致"));
      } else {
        callback();
      }
    };
    return {
      contentHeight: "",
      editUserInfoModal: false,
      resetPasswordModal: false,
      avatar: null,
      visible: false,
      reUpload: false,
      useUserInfoCSS: true,
      //显示的内容
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      imageFile: null,
      //tags
      organizations: "",
      domains: "",
      //编辑的内容
      userInfoFormItems: {
        // avatar: "",
        //用于 localUser
        userId: "",
        name: "",
        phone: "",
        subject: "",
        college: "",
      },
      //重设密码表单
      resetPwdFormItems: {
        oldPwd: "",
        newPwd: "",
        validPwd: "",
      },
      resetPwdRuleValidate: {
        oldPwd: [{ required: true, message: "密码不能为空", trigger: "blur" }],
        newPwd: [{ required: true, message: "密码不能为空", trigger: "blur" }],
        validPwd: [{ required: true, validator: validatePass, trigger: "blur" }],
      },
    };
  },
  created() {},
  mounted() {
    this.reSize();
    window.addEventListener("resize", this.reSize);
  },
  beforeDestroy: function () {
    window.removeEventListener("resize", this.reSize);
  },
  methods: {
    resizeContent() {
      if (window.innerHeight > 675) {
        this.contentHeight = window.innerHeight - 120;
      } else {
        this.contentHeight = 555;
      }
      window.onresize = () => {
        return (() => {
          this.resizeContent();
        })();
      };
    },
    reSize() {
      // if (window.innerHeight > 675) {
      //   this.contentHeight = window.innerHeight - 120 + "px";
      // } else {
      //   this.contentHeight = 675 - 120 + "px";
      // }
      if (window.innerWidth < 1200) {
        this.useUserInfoCSS = false;
      } else {
        this.useUserInfoCSS = true;
      }
    },

    showEditUserInfoModal: function () {
      this.userInfoFormItems = JSON.parse(JSON.stringify(this.userInfo));
      this.editUserInfoModal = true;
    },
    async updateUserInfo() {
      let formData = new FormData();
      formData.append("name", this.userInfoFormItems.name);
      formData.append("subject", this.userInfoFormItems.subject);
      formData.append("college", this.userInfoFormItems.college);
      if (this.reUpload == true) {
        formData.append("avatar", this.imageFile);
      }
      if (this.userInfoFormItems.avatar == "") {
        formData.append("avatarRemove", "true");
      }
      try {
        let res = await post("/visualResourceLibrary/user/update", formData);
        this.editUserInfoModal = false;
        this.$Notice.success({
          title: "修改成功",
        });
        let userData = res.data.data;
        this.userInfo = userData;
        userData["userState"] = true;
        localStorage.setItem("userInfo", JSON.stringify(res.data.data));
        location.reload();
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    showResetPwdModal: function () {
      this.resetPwdFormItems.newPwd = "";
      this.resetPwdFormItems.oldPwd = "";
      this.resetPwdFormItems.validPwd = "";
      this.resetPasswordModal = true;
    },
    async resetPwd() {
      let encodeNewPwd = md5(this.resetPwdFormItems.newPwd);
      let encodeOldPwd = md5(this.resetPwdFormItems.oldPwd);
      try {
        await get("/visualResourceLibrary/user/pwd/" + encodeOldPwd + "/" + encodeNewPwd);
        this.resetPasswordModal = false;
        this.$Notice.success({
          title: "密码修改成功!",
        });
        this.$store.commit("userLogout");
        this.$router.push({ name: "Login" });
      } catch (e) {
        this.$Message.error("密码修改失败!");
      }
    },
    selectImg: function () {
      document.getElementById("choosePicture").click();
    },
    uploadPhoto(e) {
      console.log("upload");
      // 利用fileReader对象获取file
      let file = e.target.files[0];
      let filesize = file.size;
      let filename = file.name;
      let imgcode = "";
      // 2,621,440   2M
      if (filesize > 1024 * 1024) {
        // 图片大于2MB
        this.$Message.error("size > 1MB");
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          // 读取到的图片base64 数据编码 将此编码字符串传给后台即可
          imgcode = e.target.result;
          this.reUpload = true;
          this.userInfoFormItems.avatar = imgcode;
          this.imageFile = file;
          // $("#choosePicture").val("");
        };
      }
    },
    handleView() {
      this.visible = true;
    },
    handleRemove() {
      this.userInfoFormItems.avatar = "";
      this.imageFile = null;
    },
  },
  computed: {
    avatarUrl: function () {
      let temp = this.userInfo.avatar;
      return this.$store.getters.dataSever + temp;
    },
  },
};
</script>

<style scoped>
.userInfoCard {
  background-color: white;
  border-radius: 3px;
  border: 1px solid #dadce0;
  box-shadow: 0 3.2px 7.2px 0 rgb(0 0 0 / 13%), 0 0.6px 1.8px 0 rgb(0 0 0 / 11%);
  opacity: 0.95;
}

.organization >>> .ti-input {
  display: inline-block;
  width: 469px;
  height: 32px;
  line-height: 1.5;
  padding: 4px 7px;
  font-size: 12px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  color: #515a6e;
  background-color: #fff;
  background-image: none;
  position: relative;
  cursor: text;
}

.organization >>> input {
  opacity: 0.5;
}

.formStyle {
  display: flex;
  justify-content: center;
}

.uTitle {
  padding-right: 10px;
  font-family: "Roboto Light";
  color: #999999;
  margin-left: 7%;
}

.uContent {
  color: #333333;
  margin-left: 20%;
}

.uContentIntro {
  color: #333333;
  margin-left: 10%;
}

.uContentElse {
  color: #333333;
  margin-left: 40%;
}

.uContentIntroElse {
  color: #333333;
  margin-left: 10%;
}

.uAlign {
  position: absolute;
  left: 100px;
  text-align: left;
  width: 400px;
}

.uAlignIntro {
  display: flex;
  align-items: center;
  height: 200px;
}

.selectImg:hover {
  background-color: rgba(5, 192, 255, 0.55);
  cursor: pointer;
  box-shadow: 1px 2px 5px rgb(0 0 0 / 30%) !important;
  border-radius: 100%;
}

.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.avatarImage {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.uploadAvatar {
  position: relative;
  width: 58px;
  height: 58px;
  top: 0;
  left: 0;
  outline: none;
  background-color: transparent;
  opacity: 0;
}
.uploadBox {
  display: inline-block;
  width: 58px;
  height: 58px;
  line-height: 58px;
  overflow: hidden;
  border-width: 0.75px;
  border-style: dashed;
  border-color: lightslategray;
}
</style>
